package com.api.weavernorth.action.loginLog;

import com.engine.systeminfo.web.GetOSInfoAction;
import com.weaver.general.Util;
import com.weavernorth.sysap.util.SyncUtil;
import com.weavernorth.util.Logger4jUtil;
import com.weavernorth.util.dateUtils;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;

@Path("/weavernorth/action/loginLog")
public class loginLog_mobileUser extends GetOSInfoAction {
    private Logger log = Logger4jUtil.getLoggerByName("/action/loginLog/loginLog_mobileUser/");
    @GET
    @Path("/getLoginLog")
    @Produces(MediaType.TEXT_PLAIN)
    public String getDatas(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException, DocumentException {
        log.info("获取人员登录信息：");
        String strResult="0";
        try {
            //获取当前登录人的id
            String strUserid =request.getParameter("userid");
            String cType =request.getParameter("ctype");//登录类型：pc/mobile
            //外部参数
            log.info("参数人员id:" + strUserid);
            User user = HrmUserVarify.getUser(request, response);
            if (strUserid==null||strUserid.equals("")){
                strUserid=Util.null2String(String.valueOf(user.getUID()));
            }
            log.info("当前登录人id:"+strUserid);
            String sql="select workcode,lastname from hrmresource where id='"+strUserid+"'";
            log.info("人员id："+strUserid);
            RecordSet rsUser=new RecordSet();
            rsUser.executeQuery(sql);
            rsUser.next();
            String strWorkcode="";
            String strUserName="";
            if("1".equals(strUserid)){
                strWorkcode="";
                strUserName="系统管理员";
            }else{
                strWorkcode=Util.null2String(rsUser.getString("workcode"));
                log.info("登录用户工号："+strWorkcode);
                strUserName=Util.null2String(rsUser.getString("lastname"));
                log.info("登录用户名："+strUserName);
            }
            String strSql="select sys_context('userenv','host') hostname,sys_context('userenv','ip_address') ip from dual";
            RecordSet rs=new RecordSet();
            rs.executeQuery(strSql);
            String ip = "";
            String hostname = "";
            if(rs.next()){
                hostname = rs.getString("hostname");
                ip = rs.getString("ip");
            }
            log.info("服务器ip地址"+ip);
            String date= dateUtils.getYearMonthDay();
            String time=dateUtils.getHourMs();
            String cTypes="0";
            if("mobile".equals(cType)){
                cTypes="1";
            }
            String strisExists;
            if(!strWorkcode.equals("")){
                strisExists="SELECT * FROM uf_userLoginLogs WHERE SUBSTR(createdate, 0, 10)='"+date+"' AND workcode='"+strWorkcode+"' AND fwqip='"+ip+"' and CTYPE='"+cTypes+"'";
            }else{
                strisExists="SELECT * FROM uf_userLoginLogs WHERE SUBSTR(createdate, 0, 10)='"+date+"' AND yhm='系统管理员' AND fwqip='"+ip+"' and CTYPE='"+cTypes+"'";
            }

            log.info("查询sql:"+strisExists);
            RecordSet rs_isExists=new RecordSet();
            rs_isExists.executeQuery(strisExists);
            int count=rs_isExists.getCounts();
            log.info("结果集行数："+count);
            SyncUtil syncUtil = new SyncUtil();
            //获取表的formid
            String strFormid = syncUtil.getModeIdBytableName("uf_userLoginLogs");
            if (count==0){
                //不存在就插入
                String strInsertSql="insert into uf_userLoginLogs (workcode,yhm,fwqip,khdip,createdate,formmodeid,modedatacreater,CTYPE) values('"+strWorkcode+"','"+strUserName+"','"+ip+"','"+request.getRemoteAddr()+"','"+date+" "+time+"','"+strFormid+"',1,'"+cTypes+"')";
                RecordSet rs_save=new RecordSet();
                rs_save.executeQuery(strInsertSql);
                //数据授权
                RecordSet rs_getID=new RecordSet();
                rs_getID.executeQuery("SELECT id FROM(SELECT id FROM uf_userLoginLogs ORDER BY id desc)  WHERE ROWNUM=1");
                int maxId=0;
                while (rs_getID.next()){
                    maxId= Util.getIntValue(rs_getID.getString("id"));
                }
                ModeRightInfo modeRightInfoBanc = new ModeRightInfo();
                modeRightInfoBanc.setNewRight(true);
                modeRightInfoBanc.editModeDataShare(1, Integer.parseInt(strFormid), maxId);
                strResult="ip='"+ip+"',人员登录日志记录成功！";
                log.info("人员工号："+strWorkcode+",姓名："+strUserName+",服务器ip："+ip+"登录日志记录成功！");
            }else{
                //存在就更新
                String strUpdateSql;
                if(!"".equals(strWorkcode)){
                    strUpdateSql="update uf_userLoginLogs set updatedate='"+time+"' where workcode='"+strWorkcode+"'and yhm='"+strUserName+"' and SUBSTR(createdate, 0, 10)='"+date+"' and fwqip='"+ip+"' and CTYPE='"+cTypes+"'";
                }else {
                    strUpdateSql="update uf_userLoginLogs set updatedate='"+time+"' where SUBSTR(createdate, 0, 10)='"+date+"' and yhm='"+strUserName+"' and fwqip='"+ip+"' and CTYPE='"+cTypes+"'";
                }

                RecordSet rs_update=new RecordSet();
                rs_update.executeQuery(strUpdateSql);
                strResult="ip='"+ip+"',人员登录日志更新成功！";
                log.info("人员工号："+strWorkcode+",姓名："+strUserName+",服务器ip："+ip+"登录日志更新成功！");
            }

        } catch (Exception ex) {
            log.info("获取人员id出错！"+ex.toString());
            strResult="获取人员信息出错！";
        }finally {
            if(strResult.equals("0")){
                strResult="程序出现异常！";
            }
        }
        JSONObject result_json=new JSONObject();
        result_json.put("msg",strResult);
        return result_json.toString();
    }

}
